
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  importPool;

import java.io.RandomAccessFile;
import java.sql.ResultSet;
import java.util.Hashtable;
import java.util.Vector;

import logger.PoolLogger;

import pool.bean.Rate_master_Bean;

//import control.Control;
import control.RequestParameter;
import dbmanager.DBManager;
import dbmanager.GetIdName;

public class RegisterRate 
{		
	
		private String FilePath;
		private String responsePath ;
		
		RequestParameter reqparam;
		
		private Vector<Object>jselectedVector=new Vector<Object>();			
		PoolLogger pl;
		
		public RegisterRate(String FilePath,String ResponsePath,Vector<Object> columnVector) 
		{			
			
			System.out.println("i m in RegisterRate");

			this.FilePath = FilePath;
			this.responsePath = ResponsePath;
			this.jselectedVector = columnVector;
			Register();
			
			// logger
			pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
		}
		
		
		public void Register()
		{			
			System.out.println("I m in RegisterMethod");
			pl.info("I m in RegisterMethod");
			pl.debug("I m in RegisterMethod");
			pl.warn("I m in RegisterMethod");
			pl.fatal("I m in RegisterMethod");
			pl.error("I m in RegisterMethod");
			pl.trace("I m in RegisterMethod");
				
			String line = null;			
			setRequestParameter();
			
			try 
			{				
				RandomAccessFile raf = new RandomAccessFile(FilePath,"rws");				
				RandomAccessFile RateReqResp = new RandomAccessFile(responsePath,"rws");				
				
				line=raf.readLine();
				
				String[] records = 	line.split("\t");	
				
				GetIdName gid = new GetIdName();		
				ResultSet rs = DBManager.getSelect("SELECT fieldname FROM command where lower(fieldname)='rate' and msgtype = 'rate_master' and process = 'add'");
				rs.next();
				String rateChar = rs.getString(1);
				
				rs = DBManager.getSelect("SELECT fieldname FROM command where lower(fieldname)='buysell' and msgtype = 'rate_master' and process = 'add'");
				rs.next();
				String buysellChar = rs.getString(1);				
								
				rs = DBManager.getSelect("SELECT fieldname FROM command where msgtype = 'rate_master' and process = 'add' order by order1");
				ResultSet rs1 = DBManager.getSelect("select distinct buysell from rate_master");
				
				String itemline=" ";
				String[] recordsitem ;
				
				while((itemline=raf.readLine())!=null)
				{		
					
					Hashtable<Object,Object> RateHash = new Hashtable<Object, Object>();
					Vector<Object> RateVector = new Vector<Object>();					
					Vector<Object> tempVector = new Vector<Object>();
					recordsitem = itemline.split("\t");
					
					for(int i=0; i<jselectedVector.size(); i++)
					{					
						String strIndex = jselectedVector.get(i).toString();
						tempVector.add(strIndex);
						int index = Integer.parseInt(strIndex);
						String rateObject = records[index];
						rateObject = rateObject.trim();
						
						while (rs.next())
						{
							String strRate = rs.getString(1);
							if(rateObject.equalsIgnoreCase(strRate))
							{
								RateHash.put(rateObject,recordsitem[index]);
								jselectedVector.remove(i);
								jselectedVector.insertElementAt("",i);												
								break;
							}
						}
						rs.beforeFirst();
					}
					
					for(int i=0; i<jselectedVector.size(); i++)
					{
						if(!jselectedVector.get(i).toString().equalsIgnoreCase(""))
						{							
							String strIndex = jselectedVector.get(i).toString();							
							int index = Integer.parseInt(strIndex);
							String rateObject = records[index];
							rateObject = rateObject.trim();
							
							String rateId = gid.getId(rateObject);
							while (rs1.next())
							{
								String strBuy = rs1.getString(1);						
								if(rateId.equals(strBuy))
								{
									RateHash.put(buysellChar,rateObject);
									RateHash.put(rateChar,recordsitem[index]);
									
									Hashtable<Object,Object> temp = new Hashtable<Object, Object>();
									temp.putAll(RateHash);
									RateVector.add(temp);
									
									RateHash.remove(buysellChar);
									RateHash.remove(rateChar);											
									break;
								}
							}					
							rs1.beforeFirst();												
						}						
					}
					
					RateReqResp.seek(RateReqResp.length());
					RateReqResp.writeBytes("\nRequest :"+"\n"+RateVector+"\n");
					
					StringBuffer sbr = new StringBuffer();
					Rate_master_Bean rmb = new Rate_master_Bean();
					rmb.initPool();
					rmb.setReqParam(reqparam);
					rmb.setPropertyVector(RateVector);
					sbr.append(rmb.insert());
					
					RateReqResp.writeBytes("Response :"+"\n"+sbr+"\n"+"\n");
					
					jselectedVector = tempVector;
				}				
			}
			catch (Exception e) {
				// TODO: handle exception
			}
		}	
		
		
		public void Registertem()
		{
			
			System.out.println("I m in RegisterMethod");
			pl.info("I m in RegisterMethod");
			pl.debug("I m in RegisterMethod");
			pl.warn("I m in RegisterMethod");
			pl.fatal("I m in RegisterMethod");
			pl.error("I m in RegisterMethod");
			pl.trace("I m in RegisterMethod");
			String line = null;
			
			Hashtable<Object,Object> RateHash = new Hashtable<Object, Object>();
			
			setRequestParameter();
			try 
			{
				
				RandomAccessFile raf = new RandomAccessFile(FilePath,"rws");				
				RandomAccessFile RateReqResp = new RandomAccessFile(responsePath,"rws");				
				
				line=raf.readLine();
				
				StringBuffer strbfr = new StringBuffer();
				String[] records = 	line.split("\t");			
								
				ResultSet rs = DBManager.getSelect("SELECT fieldname FROM command where lower(fieldname)='rate' and msgtype = 'rate_master' and process = 'add'");
				rs.next();
				String rateChar = rs.getString(1);
				
				rs = DBManager.getSelect("SELECT fieldname FROM command where lower(fieldname)='buysell' and msgtype = 'rate_master' and process = 'add'");
				rs.next();
				String buysellChar = rs.getString(1);				
				
				String itemline=" ";
				String[] recordsitem ;
				
				rs = DBManager.getSelect("SELECT fieldname FROM command where msgtype = 'rate_master' and process = 'add' order by order1");
				while((itemline=raf.readLine())!=null)
				{
					
					RateHash = new Hashtable<Object, Object>();
					Vector<Object> RateVector = new Vector<Object>();
					
					recordsitem = itemline.split("\t");
					while (rs.next())
					{
						String fieldname = rs.getString(1);						
						
						for(int i=0;i<records.length;i++)
						{							
							if (records[i].equalsIgnoreCase(fieldname)) 
							{								
								RateHash.put(records[i],recordsitem[i]);
								
								strbfr.append(records[i]);
								strbfr.append(",");
								
								records[i]="";								
								break;
							}							
						}						
					}
					rs.beforeFirst();
					
					for(int i=0;i<records.length;i++)
					{
						if(!records[i].equalsIgnoreCase(""))
						{
							RateHash.put(buysellChar,records[i]);
							RateHash.put(rateChar,recordsitem[i]);
							
							Hashtable<Object,Object> temp = new Hashtable<Object, Object>();
							temp.putAll(RateHash);
							RateVector.add(temp);
							
							strbfr.append(records[i]);
							strbfr.append(",");
							
							RateHash.remove(buysellChar);
							RateHash.remove(rateChar);							
						}
					}	
					
					RateReqResp.seek(RateReqResp.length());
					RateReqResp.writeBytes("\nRequest :"+"\n"+RateVector+"\n");
					
					StringBuffer sbr = new StringBuffer();
					Rate_master_Bean rmb = new Rate_master_Bean();
					rmb.initPool();
					rmb.setReqParam(reqparam);
					rmb.setPropertyVector(RateVector);
					sbr.append(rmb.insert());
					
					RateReqResp.writeBytes("Response :"+"\n"+sbr+"\n"+"\n");
					
					strbfr = strbfr.deleteCharAt(strbfr.length()-1);
					
					records = strbfr.toString().split(",");
					strbfr = new StringBuffer();
				}					
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}			
		}
		
		private void setRequestParameter()
		{
			reqparam = new RequestParameter();
			
			reqparam.setUsername("+911234567891");
			reqparam.setMessage("System Message");
			reqparam.setPassword("891");
			reqparam.setRequest("rate_master");
			reqparam.setProcess("add");			
		}
		
		
		/*public int Register()
		{
			System.out.println("I m in RegisterMethod");
			int Count=0;
			String line = null;
			try 
			{
<<<<<<< .mine
				
				RandomAccessFile raf = new RandomAccessFile(FilePath,"rws");
				//RandomAccessFile log = new RandomAccessFile(logPath,"rws");
				String errorPath = "";
				RandomAccessFile Error = new RandomAccessFile(errorPath,"rws");
				RandomAccessFile RateReqResp = new RandomAccessFile(responsePath,"rws");				
				
=======
>>>>>>> .r1776
				line=raf.readLine();
				
				String[] records = line.split("\t");
				
				String col[] = new String[8];
				col[0] = records[0];	//Itemcode
				col[1] = records[1];	//Unit
				col[2] = records[2];	//Usergroup
				col[3] = records[3];	//Buy
				col[4] = records[4];	//Sell
				//col[5] = records[5];	//MRP
				//col[6] = records[6];     //Vat
				//col[7] = records[7];	//Discount
				col[5] = records[5];	//Discount
				
				ResultSet rs = db.getSelect("SELECT * FROM command where lower(fieldname)= lower('"+col[0]+"') and msgtype = 'rate_master'");
				rs.next();
				col[0] = rs.getString("spchar");
				
				rs = db.getSelect("SELECT * FROM command where lower(fieldname)= lower('"+col[1]+"') and msgtype = 'rate_master'");
				rs.next();
				col[1] = rs.getString("spchar");
				
				rs = db.getSelect("SELECT * FROM command where lower(fieldname)=lower('"+col[2]+"') and msgtype = 'rate_master'");
				rs.next();
				col[2] = rs.getString("spchar");
			
				rs = db.getSelect("SELECT * FROM command where lower(fieldname)='rate' and msgtype = 'rate_master'");
				rs.next();
				String rateChar = rs.getString("spchar");
				
				rs = db.getSelect("SELECT * FROM command where lower(fieldname)='buysell' and msgtype = 'rate_master'");
				rs.next();
				String buysellChar = rs.getString("spchar");				
				
					String userid = "systemuser";
				Uservalidation getpass = new Uservalidation(db);
				String password = getpass.getPasword(userid);
				
				String itemline=" ";
				String[] recordsitem ;
				String[] recordsitemselected ;
				String indexofselecteditems = " ";
				String[] recordssitemselected ;
				String selecteditem=" ";
				while((itemline=raf.readLine())!=null)
				{
						String message ="";
						try 
						{
								String propString = "";
								recordsitem = itemline.split("\t");
								
								String indexofitem=" ";
								String itemValue=" ";
								//String itemfieldName=" ";
								System.out.println("jselectedVector*******"+jselectedVector);
								for(int k=0;k<jselectedVector.size();k++)
								{	
										//System.out.println("IndexVector======="+indexVector);
										indexofitem = jselectedVector.get(k).toString();
										//itemfieldName=records[Integer.parseInt(indexofitem)];
										itemValue=recordsitem[Integer.parseInt(indexofitem)];
										if(selecteditem.equals(" "))
										{
											selecteditem=itemValue;
										}
										else
										{
											selecteditem=selecteditem+','+itemValue;
										}
									
								}
								
								recordsitemselected=selecteditem.split(",");
								for(int j=0;j<jselectedVector.size();j++)
								{
									if(indexofselecteditems.equals(" "))
									{
										indexofselecteditems=jselectedVector.get(j).toString();
									}
									else
									{
										indexofselecteditems=indexofselecteditems+','+jselectedVector.get(j).toString();
									}
								
								}
								recordssitemselected=indexofselecteditems.split(",");
								
																			
								int i=0;
								for(int j=0;j<recordssitemselected.length;j++)
								{
										String indexstr=" ";
										int index;
										indexstr=recordssitemselected[j];
										index=Integer.parseInt(indexstr);
										
										if(index<3)
										{
									
												try 
												{
											
													String pv = recordsitemselected[i].trim();
													if (pv.length() == 0)
														pv = "0";
													propString = propString + col[i].trim()+ "\"" + pv + "\"";
													 i++;
											
												} catch (Exception e)
												{
													String pv = "0";
													propString = propString + col[i].trim()+ "\"" + pv + "\"";
												}
										}
										else
										{
											break;
										}
									}
									
								for(int k=0;k<recordssitemselected.length;k++)
								{	
									String indexstr=" ";
									int index;
									indexstr=recordssitemselected[k];
									index=Integer.parseInt(indexstr);
									if(index>=3)
									{
										String temp="";
										try
										{
											String pv = recordsitemselected[i].trim();
											
											if (pv.length() != 0)
											{
												message = "11 rate_master add"+propString+rateChar+"\""+pv+"\""+buysellChar+"\""+records[index].trim()+"\""+"#"+"605";
												
												RateReqResp.seek(RateReqResp.length());
												
												RateReqResp.writeBytes("\nRequest :"+"\n"+message+"\n");
												Control controlClassObj = new Control("+919922918605",message,db);
												controlClassObj.messageProcessing();
												temp = controlClassObj.requestProcess().toString();
												
												RateReqResp.writeBytes("Response :"+"\n"+temp+"\n"+"\n");
												db.pLog.addLog();
												if(temp.contains("error"))
													Error.writeBytes(message+"\n");
										  }
										}
										catch (Exception e) 
										{
											Error.writeBytes(message+"\n");
										}
										System.out.println("MESSGE IS :"+message);
									}								
								}							
							Count++;
						} 
								
						catch (Exception e) 
						{
							Error.writeBytes(message+"\n");
						}
				}
			//	log.close();
				Error.close();
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			return Count;
		}*/
		
		public static void main(String[] args) 
		{
			
			
			Vector<Object>jselected=new Vector<Object>();
			jselected.add("0");
			jselected.add("1");
			jselected.add("2");
			//jselected.add("3");
			jselected.add("5");
			jselected.add("6");
			

		
			String filePath = ImportFilePath.INPUTPATH+ "Item.txt";
			String resPath = ImportFilePath.RATERESPONSEPATH;

			@SuppressWarnings("unused")
			RegisterRate reg = new RegisterRate(filePath,resPath,jselected);
			
			//reg.Register();
			//System.out.println("RAte Counter :"+reg.Register());
			
		}
}